package com.weishenai.customerassistant.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weishenai.customerassistant.entity.sys.SysMenuEntity;
import com.weishenai.customerassistant.entity.sys.SysRoleEntity;
import com.weishenai.customerassistant.entity.sys.SysUserEntity;
import com.weishenai.customerassistant.mapper.SysUserMapper;
import com.weishenai.customerassistant.service.SysMenuService;
import com.weishenai.customerassistant.service.SysRoleService;
import com.weishenai.customerassistant.service.SysUserService;
import com.weishenai.customerassistant.utils.JwtUtils;
import com.weishenai.customerassistant.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author weishenai
 * @since 2021-11-27
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity> implements SysUserService {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public SysUserEntity getByUsername(String username) {
        return this.baseMapper.selectOne(Wrappers.lambdaQuery(SysUserEntity.class)
                .eq(SysUserEntity::getUsername, username));
    }

    //获取 角色信息与菜单信息
    @Override
    public String getUserAuthorityInfo(Long userId) {
        SysUserEntity sysUserEntity = this.getById(userId);
        String authority = null;
        if (redisUtils.hasKey("GrantedAuthority" + sysUserEntity.getUsername())) {
            authority = (String) redisUtils.get("GrantedAuthority:" + sysUserEntity.getUsername());
        } else {
            //获取校色编码
            List<SysRoleEntity> roles = sysRoleService.list(new QueryWrapper<SysRoleEntity>()
                    .inSql("id", "select role_id from sys_user_role where user_id = " + userId));

            if (roles.size() > 0) {
                String roleCodes = roles.stream().map(r -> "ROLE_" + r.getCode()).collect(Collectors.joining(","));
                authority = roleCodes.concat(",");
            }

            // 获取菜单操作编码
            List<Long> menuIds = sysUserMapper.getNavMenuIds(userId);
            if (menuIds.size() > 0) {

                List<SysMenuEntity> menus = sysMenuService.listByIds(menuIds);
                String menuPerms = menus.stream().map(m -> m.getPerms()).collect(Collectors.joining(","));

                authority = authority.concat(menuPerms);
            }

            redisUtils.set("GrantedAuthority:" + sysUserEntity.getUsername(), authority, 60 * 60);
        }
        return authority;
    }

    @Override
    public void clearUserAuthorityInfo(String username) {
        redisUtils.del("GrantedAuthority:" + username);

    }

    @Override
    public void clearUserAuthorityInfoByRoleId(Long roleId) {
        List<SysUserEntity> sysUsers = this.list(new QueryWrapper<SysUserEntity>()
                .inSql("id", "select user_id from sys_user_role where role_id = " + roleId));

        sysUsers.forEach(u -> {
            this.clearUserAuthorityInfo(u.getUsername());
        });
    }

    @Override
    public void clearUserAuthorityInfoByMenuId(Long menuId) {
        List<SysUserEntity> sysUsers = sysUserMapper.listByMenuId(menuId);

        sysUsers.forEach(u -> {
            this.clearUserAuthorityInfo(u.getUsername());
        });
    }

    @Override
    public Page<SysUserEntity> selectPage(String name, Integer currentPage, Integer pageSize) {
        return this.page(new Page<>(currentPage, pageSize),
                Wrappers.lambdaQuery(SysUserEntity.class)
                        .like(StrUtil.isNotBlank(name), SysUserEntity::getUsername, name));
    }
}
